# !/usr/bin/env Python
# -*-utf-8-*-
# 51memo0.28.py
# 使用面向对象技术进行重构，增加存盘和读盘功能
# author:zby

import string
import sys
import re
import pickle


class Memo:
    def __init__(self, id, name, date, thing):
        'memo记录的初始化方法'
        self._id = id
        self.name = name
        self.date = date
        self.thing = thing
        self.memo = {
            'id':id,
            'name':name,
            'thing':thing ,
            'date':date
        }
    
    @property
    def id(self):
        '使_id变为只读的魔术写法'
        return self._id
    
    def __eq__(self, other):
        if self.memo == other.memo:
            return True
        else:
            return False

class MemoAdmin:
    def __init__(self):
        '初始化管理函数的list'
        self.memo_list = []
        self.load_data()
        self.__author__ = 'zhaoboyuan'

    
    def start(self):
        self.welcome()
        self.print_memo()
        if len(sys.argv) == 1:
            self.help()
            print(sys.argv)
        else:
            if sys.argv[1] in {'-a', '--add'}:
                id = int(input('请输入想要添加的id'))
                name = input('请输入想要添加的name')
                date = input('请输入想要添加的date')
                thing = input('请输入想要添加的thing')
                temp = Memo(id, name, date, thing)
                self.add(temp)            
            elif sys.argv[1] in {'-d', '--delete'}:
                id = int(input('请输入想要删除记录的id'))
                self.delete(id)
            elif sys.argv[1] in {'-h', '--help'}:
                self.help()
            elif sys.argv[1] in {'-f', '--find'}:
                id = int(input('请输入查找的id'))
                name = input('请输入查找的name')
                date = input('请输入查找的date')
                thing = input('请输入查找的thing')
                find_temp = self.find(id, name, thing, date)
                if find_temp != -1:
                    print(find_temp)
            elif sys.argv[1] in {'-m', '--modify'}:
                id_ahead = int(input('请输入修改前的id'))
                id = int(input('请输入修改后的id'))
                name = input('请输入修改后的name')
                date = input('请输入修改后的date')
                thing = input('请输入修改后的thing')
                temp = Memo(id, name, date, thing)
                self.modify(id_ahead, temp)
            else:
                self.help()
        self.save_data()

    def help(self):
        print("""usage:
        -a or --add 增加备忘录事件
        -d or --delete 删除备忘录事件
        -m or --modify 修改备忘录事件
        -f or --find 查找备忘录事件
        -h or --help 查看帮助
        """)

    def welcome(self):
        """欢迎词函数"""
        desc = '51memo'.center(30,'-')
        print(desc)
        welcome = 'welcome'
        print(f'{welcome}', self.__author__)

    def print_memo(self):
        '打印所有的记录'
        num = 0
        for m in self.memo_list:
            num += 1
            print('%s:%s' % (num, m))
        print(f'共{len(self.memo_list)}条待办事项')            


    def add(self, Memo_temp):
        '增加记录，如果增加成功返回True，否则返回False'
        try:
            # one = '{date},act{action},timespan{time}'.format(date=in_date, thing=in_thing, time=in_time)
            for m in self.memo_list:
                if m['id'] == Memo_temp.id:
                    print('添加的id已经存在，不能再次添加！')
                    return False

            self.memo_list.append(Memo_temp.memo) 
            self.print_memo()
            return True
        except Exception as e:
            print('添加memo出错',e)
            return False

    def delete(self, id):
        '删除记录，id为欲删除的记录的id，如果删除成功返回True，否则返回False'
        if isinstance(id, int):
            for m in self.memo_list:
                if m['id'] == id:
                    self.memo_list.remove(m)
                    self.print_memo()
                    return True
            print('输入的id不存在')
            return False
        elif isinstance(id, dict):
            if id in self.memo_list:
                self.memo_list.remove(id)
                self.print_memo()
                return True
            else:
                print('输入的id不存在')
                return False
        else:
            print('id的类型不正确')
            return False


    def modify(self, id, Memo_temp):
        '修改一条记录，id 为修改记录的id，Memo为修改后的值'
        for m in self.memo_list:
                if m['id'] == id:
                    self.memo_list[self.memo_list.index(m)] = Memo_temp.memo
                    self.print_memo()
                    return True
        print('修改不成功，不存在id')
        return False

    def find(self, id, name, thing, date):
        '查找记录函数，如果查找到了一条记录返回该记录，否则返回-1'
        Memo_temp = Memo(id, name, thing, date)
        for m in self.memo_list:
                if m['id'] == id:
                    self.memo_list[self.memo_list.index(m)] = Memo_temp.memo
                    return m
        print('不存在id')
        return -1

    def save_data(self):
        '存储memo_list到memo_list.pkl中'
        with open('memo_list.pkl', 'wb') as f:
            pickle.dump(self.memo_list, f)

    def load_data(self):
        '读取memo_list.pkl的数据到self.memo_list中'
        try:
            with open('memo_list.pkl',  'rb') as f:
                self.memo_list = pickle.load(f)
        except Exception as e:
            print(e)
        

def __main__():
    '主函数，程序的主入口'
    admin = MemoAdmin()
    admin.start()
if __name__ == "__main__":
    __main__()


    
